package com.vanke.devops.domain.manager.docker.extend.exec;

import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.util.FiltersEncoder;
import com.github.dockerjava.jaxrs.AbstrSyncDockerCmdExec;
import com.vanke.devops.domain.manager.docker.extend.command.ListServicesCmd;
import com.vanke.devops.domain.manager.docker.extend.model.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.util.List;

import static com.google.common.net.UrlEscapers.urlPathSegmentEscaper;

/**
 * @author 陈景阳
 * @since 2018/6/7
 */
public class ListServicesCmdExec extends AbstrSyncDockerCmdExec<ListServicesCmd,List<Service>> implements ListServicesCmd.Exec{

    private static final Logger LOGGER = LoggerFactory.getLogger(ListServicesCmdExec.class);

    public ListServicesCmdExec(WebTarget baseResource, DockerClientConfig dockerClientConfig) {
        super(baseResource, dockerClientConfig);
    }

    @Override
    protected List<Service> execute(ListServicesCmd command) {
        WebTarget webTarget = getBaseResource().path("/services");
        LOGGER.trace("GET: {}", webTarget);

        if (command.getFilters() != null && !command.getFilters().isEmpty()) {
            webTarget = webTarget.queryParam("filters",
                    urlPathSegmentEscaper().escape(FiltersEncoder.jsonEncode(command.getFilters())));
        }
        List<Service> images = webTarget.request().accept(MediaType.APPLICATION_JSON).get(new GenericType<List<Service>>() {
        });
        LOGGER.trace("Response: {}", images);
        return images;
    }
}
